﻿using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.Interfaces;
using BaseData.ReadAPI.Applications.Commands.Role;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace BaseData.ReadAPI.Applications.CommandHandlers.Role
{
    public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Roles> roleRep;

        public AddRoleCommandHandler(IBaseRepository<Roles> roleRep)
        {
            this.roleRep = roleRep;
        }

        public async Task<APIResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var res = await roleRep.GetAll().FirstOrDefaultAsync(x=>x.RoleName==request.Data.RoleName);
                if (res!=null)
                {
                    return new APIResult<int>
                    {
                        Code = CodeEnum.Failed,
                        Message = "角色名称已存在",
                        Data = -1
                    };
                }
                request.Data.MemberCount = 100;
                request.Data.UpdateTime = DateTime.Now;
                request.Data.RoleState = true;
                await roleRep.AddAsync(request.Data);
                return new APIResult<int>
                {
                    Code = CodeEnum.Success,
                    Message = "添加角色成功",
                    Data = 1
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
